<?php
/**
 *
 * Author: Lyu
 * Date: 2023/8/8
 * Time: 10:12
 */
namespace App\Model\Core\Admin;

use App\Model\CoreModel;

class AdminFileModel extends CoreModel
{

    protected string $table = 'admin_file';
    const EXPORT_USER = 1;//用户
    const IMPORT_USER = 1;//用户

    const OPERATE_IMPORT = 1;//导入
    const OPERATE_EXPORT = 2;//导出
    public static $export_type = [
        self::EXPORT_USER => '用户',
    ];
    public static $import_type = [self::IMPORT_USER => '用户'];
    public static $operate_type = [self::OPERATE_IMPORT => '导入', self::OPERATE_EXPORT => '导出'];
    const STATUS_WAIT = 1;
    const STATUS_PROCESSING = 2;
    const STATUS_COMPLETE = 3;
    const STATUS_FAIL = 4;
    const STATUS_DELETED = 5;
    const STATUS_CANCELD = 6;
    public static $status = [
        self::STATUS_WAIT => '待处理', self::STATUS_PROCESSING => '数据处理中', self::STATUS_COMPLETE => '处理完成',
        self::STATUS_FAIL => '处理失败', self::STATUS_DELETED => '已删除', self::STATUS_CANCELD => '已取消'
    ];

    /**
     * 获取一条数据
     * @param int $file_id
     * @param bool $is_cache
     * @param bool $is_lock
     * @return array
     */
    public function getOne(int $file_id, bool $is_cache = true, bool $is_lock = false): array
    {
        if ($file_id < 0) {
            return [];
        }
        return $this->cache($file_id, function () use ($file_id, $is_lock) {
            $query_obj = $this->getConnectionTable()->where('file_id', $file_id);
            if ($is_lock) {
                $query_obj->lockForUpdate();
            }
            return obj_to_array($query_obj->first());
        }, $is_cache);
    }

    /**
     * 添加单条数据
     * @param array $data
     * @return false|int
     */
    public function addOne(array $data): bool|int
    {
        if (empty($data)) {
            return false;
        }
        return $this->getConnectionTable()->insertGetId($data);
    }

    /**
     * 更新单条数据
     * @param int $file_id
     * @param array $data
     * @return false|int
     */
    public function updateOne(int $file_id, array $data): bool|int
    {
        if ($file_id <= 0 || empty($data)) {
            return false;
        }
        $res = $this->getConnectionTable()->where('file_id', $file_id)->update($data);
        if ($res) {
            $this->cleanCache($file_id);
        }
        return $res;
    }

    /**
     * 删除单条数据
     * @param int $file_id
     * @return false|int
     */
    public function deleteOne(int $file_id): bool|int
    {
        if ($file_id <= 0) {
            return false;
        }
        $res = $this->getConnectionTable()->where('file_id', $file_id)->delete();
        if ($res) {
            $this->cleanCache($file_id);
        }
        return $res;
    }
}
